package me.xue.communityhealth.admin.controller;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import lombok.extern.slf4j.Slf4j;
import me.xue.communityhealth.data.Pager;
import me.xue.communityhealth.model.User;
import me.xue.communityhealth.service.UserService;
import me.xue.communityhealth.util.ApplicationUtil;
import me.xue.communityhealth.util.BCryptPasswordEncoder;
import me.xue.communityhealth.util.FileUtil;
import me.xue.communityhealth.util.Md5Util;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.validation.Valid;
import java.util.Date;

@Controller
@Slf4j
public class UserController {

    private final UserService userService;

    @Autowired
    public UserController(UserService userService) {
        this.userService = userService;
    }

    @GetMapping("/users")
    public String all(@RequestParam(value = "page", required = false, defaultValue = "1") Integer page,
                      Model model) {
        //TODO 可配置
        PageHelper.startPage(page, 20);
        Page<User> userPage = userService.pagedUsers();
        model.addAttribute("users", userPage.getResult());
        Pager pager = new Pager(userPage.getPages(), userPage.getPageNum());
        model.addAttribute("pager", pager);
        return "users";
    }

    @GetMapping("/user/add")
    public String addPage(Model model) {
        model.addAttribute("user", new User());
        return "user_edit";
    }

    @PostMapping("/user")
    public String add(@Valid User user, BindingResult bindingResult,
                      @RequestParam(value = "portraitFile", required = false, defaultValue = "null") MultipartFile multipartFile) {
        if (bindingResult.hasErrors()) {
            log.error("添加用户失败 {}", bindingResult.getAllErrors());
            return "user_edit";
        }
        user.setPortrait(userService.savePortrait(multipartFile, getName(user.getName())));
        BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder();
        //初始密码
        user.setPassword(bCryptPasswordEncoder.encode("000000"));
        int saved = userService.save(user);
        if (saved == 1) {
            return "redirect:/users";
        }
        return "user_edit";
    }

    @DeleteMapping("/user/{id:\\d+}")
    @ResponseBody
    public String delete(@PathVariable("id") Integer id) {
        User user = userService.findOne(id);
        int deleted = userService.delete(id);
        if (deleted == 1) {
            userService.deletePortrait(user.getPortrait());
            return "success";
        }
        return "fail";
    }

    @GetMapping("/user/{id:\\d+}/edit")
    public String updatePage(@PathVariable("id") Integer id, Model model) {
        User user = userService.findOne(id);
        model.addAttribute("user", user);
        return "user_edit";
    }

    @PutMapping("/user")
    public String update(@Valid User user, BindingResult bindingResult,
                         @RequestParam(value = "portraitFile", required = false, defaultValue = "null") MultipartFile multipartFile) {
        if (bindingResult.hasErrors()) {
            return "user_edit";
        }
        if (multipartFile != null && !multipartFile.isEmpty()) {
            user.setPortrait(FileUtil.saveMultipartFile(multipartFile, ApplicationUtil.getPortraitPath().getAbsolutePath(), user.getPortrait()));
        }
        int updated = userService.update(user);
        if (updated == 1) {
            return "redirect:/users";
        }
        return "user_edit";
    }

    private String getName(String fileName) {
        return Md5Util.getHashKey(fileName + new Date().toString());
    }
}
